/**
 * 中间件索引文件
 */
const express = require('express');
const helmet = require('helmet');
const getLoggerMiddleware = require('./logger');
const getCorsMiddleware = require('./cors');
const errorHandler = require('./error-handler');
const createStaticFilesMiddleware = require('./static-files');

/**
 * 设置全局中间件
 * @param {Express.Application} app - Express应用实例
 * @param {Object} config - 应用配置
 */
const setupMiddleware = (app, config) => {
  // 基础中间件
  app.use(helmet({ contentSecurityPolicy: false })); // 安全性头部，禁用CSP以便Next.js应用正常工作
  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));
  
  // 日志中间件
  app.use(getLoggerMiddleware(config.nodeEnv));
  
  // CORS中间件
  app.use(getCorsMiddleware(config.enableCors));
  
  return app;
};

/**
 * 设置错误处理中间件
 * @param {Express.Application} app - Express应用实例
 */
const setupErrorHandlers = (app) => {
  // 全局错误处理器应该是最后添加的中间件
  app.use(errorHandler);
  
  return app;
};

module.exports = {
  setupMiddleware,
  setupErrorHandlers,
  createStaticFilesMiddleware
}; 